import { useTheme } from "@emotion/react";
import { Button, TextField } from "@mui/material";
import { Box } from "@mui/system";
import { useMutation, useQuery } from "@tanstack/react-query";
import MarkdownEditor from "@uiw/react-markdown-editor";
import { useSnackbar } from "notistack";
import React from "react";
import { useState } from "react";
import { useEffect } from "react";

import { useContext } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Loading from "../../../components/loading";
import LoadingButton from "../../../components/LoadingButton";
import {
  BLOG_PUBLISH_URL,
  BLOG_UPLOAD_URL,
  BLOG_URL,
} from "../../../constants/url";
import { queryClient } from "../../../query/CustomQueryClient";
import { getQueryFn } from "../../../query/getQueryFn";
import { postQueryFn } from "../../../query/postQueryFn";
import { TitleContext } from "../../../router";
import "./BlogEditor.css";
export default function BlogEditor() {
  const titleContext = useContext(TitleContext);
  useEffect(() => {
    titleContext.setnowTitle(0);
    queryClient.clear();
  }, []);
  const navigate = useNavigate();
  const [title, setTitle] = useState("");
  const [markdown, setMarkdown] = useState("");
  const [myuploadSuccess, setMyuploadSuccess] = useState(false);
  const passageId = useParams(); //文章id

  useEffect(() => {
    window.onbeforeunload = () => {
      return "离开页面会导致修改内容丢失，你确定要离开吗？";
    };
    return () => {
      window.onbeforeunload = null;
    };
  }, []);

  const {
    isFetching: downFetching,
    isSuccess: downSuccess,
    data: downData,
  } = useQuery(
    [BLOG_URL, { params: { bid: passageId.id }, useToken: true }],
    getQueryFn
  );

  useEffect(() => {
    if (downSuccess) {
      //
      if (passageId.id != -1) {
        setTitle(downData.data.data[0].title);
        setMarkdown(downData.data.data[0].content);
      }
    }
  }, [downSuccess]);

  // useEffect(() => {
  //   return window.alert("你确定要离开吗?");
  // }, []);

  const handleBack = () => {
    navigate(-1);
  };

  const {
    isLoading: uploadLoading,
    isSuccess: uploadSuccess,
    mutate: uploadMutate,
  } = useMutation(["uploadBlog"], postQueryFn);

  useEffect(() => {
    if (uploadSuccess) {
      if (passageId.id != -1) {
        setMyuploadSuccess(true);
        setTimeout(() => {
          setMyuploadSuccess(false);
        }, 1500);
      } else {
        enqueueSnackbar("发表成功", { variant: "success" });
        navigate(-1);
      }
    }
  }, [uploadSuccess]);

  const { enqueueSnackbar } = useSnackbar();
  const handleUpload = () => {
    //

    if (title == "" || title == null) {
      enqueueSnackbar("题目和内容不能为空", { variant: "warning" });
      return;
    }

    uploadMutate({
      params: {
        title: title,
        content: markdown,
      },
      Key: [
        passageId.id != -1
          ? BLOG_UPLOAD_URL + "/" + passageId.id
          : BLOG_PUBLISH_URL,
        { useToken: true },
      ],
    });
  };

  document.onkeydown = function (e) {
    var keyCode = e.keyCode || e.which || e.charCode;
    var ctrlKey = e.ctrlKey || e.metaKey;
    if (ctrlKey && keyCode == 83) {
      if (passageId.id != -1) handleUpload();
      e.preventDefault();
      return false;
    }
    return true;
  };
  const theme = useTheme();
  useEffect(() => {
    //
    document.documentElement.setAttribute(
      "data-color-mode",
      theme.palette.mode
    );
  }, [theme]);
  useEffect(() => {
    return () => {
      document.onkeydown = null;
    };
  }, []);

  const handleTitle = (e) => {
    if (e.target.value.length > 40) {
      //
      return;
    }
    setTitle(e.target.value);
  };

  return (
    <div>
      {downFetching && <Loading />}
      {downSuccess && (
        <div>
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <TextField
              // fullWidth

              label="题目"
              onChange={handleTitle}
              value={title}
              sx={{ marginBottom: 4, width: "80%", minWidth: "800px" }}
              helperText={title.length == 40 ? "*题目长度最多为40个字" : null}
            />

            <Box sx={{ width: "80%", minWidth: "800px" }}>
              <MarkdownEditor
                style={{
                  minHeight: "400px",
                }}
                value={passageId.id != -1 ? downData.data.data[0].content : ""}
                visible={true}
                onChange={(e) => {
                  setMarkdown(e);
                }}
              />
            </Box>
          </Box>
          <Box
            sx={{
              marginTop: "30px",
              flexDirection: "row",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Button onClick={handleBack} variant="outlined">
              返回
            </Button>
            <LoadingButton
              isFetching={uploadLoading}
              isSuccess={myuploadSuccess}
              showRight={true}
              titler={
                passageId.id != -1
                  ? !myuploadSuccess
                    ? "保存更改"
                    : "保存成功"
                  : !myuploadSuccess
                  ? "发表"
                  : "发表成功"
              }
              clickr={handleUpload}
            ></LoadingButton>
          </Box>
        </div>
      )}
    </div>
  );
}
